<template>
  <div>
    <div class="mb-6 text-sm text-gray-500 flex items-center">
      <router-link to="/dashboard" class="hover:text-gray-700">控制台</router-link>
      <i class="fas fa-chevron-right mx-2"></i>
      <span class="text-gray-900 font-medium">缺陷管理</span>
    </div>

    <div class="flex items-center justify-between mb-4">
      <h1 class="text-2xl font-bold text-gray-900">缺陷管理</h1>
      <div class="flex gap-2">
        <button @click="handleAddDefect" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2">
          <i class="fas fa-plus"></i><span>新建缺陷</span>
        </button>
        <button @click="handleBatchDelete" v-if="selectedDefects.length > 0" class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700 transition-colors flex items-center gap-2">
          <i class="fas fa-trash"></i><span>批量删除</span>
        </button>
        <button @click="handleExport" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors flex items-center gap-2">
          <i class="fas fa-download"></i><span>导出数据</span>
        </button>
      </div>
    </div>

    <!-- 筛选工具栏 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-4">
      <div class="flex flex-wrap items-center gap-3">
        <select v-model="searchForm.level" @change="handleSearch" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
          <option value="">全部等级</option>
          <option v-for="level in levelOptions" :key="level.value" :value="level.value">{{ level.label }}</option>
        </select>
        <select v-model="searchForm.type" @change="handleSearch" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
          <option value="">全部类型</option>
          <option v-for="type in typeOptions" :key="type.value" :value="type.value">{{ type.label }}</option>
        </select>
        <select v-model="searchForm.status" @change="handleSearch" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
          <option value="">全部状态</option>
          <option v-for="status in statusOptions" :key="status.value" :value="status.value">{{ status.label }}</option>
        </select>
        <div class="relative">
          <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
          <input v-model="searchForm.keyword" @keyup.enter="handleSearch" placeholder="搜索缺陷编号、线路名称或描述" class="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"/>
        </div>
        <button @click="handleSearch" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2">
          <i class="fas fa-search"></i><span>搜索</span>
        </button>
        <button @click="handleReset" class="text-gray-600 hover:text-gray-800 flex items-center gap-2">
          <i class="fas fa-undo"></i><span>重置</span>
        </button>
        <button @click="handleRefresh" class="text-blue-600 hover:text-blue-800 flex items-center gap-2">
          <i class="fas fa-sync-alt"></i><span>刷新</span>
        </button>
      </div>
    </div>

    <!-- 列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
      <div class="px-6 py-3 border-b border-gray-200 flex items-center justify-between">
        <h3 class="text-lg font-semibold">缺陷列表</h3>
        <div class="text-sm text-gray-500">
          共 {{ pagination.total }} 条
          <span v-if="selectedDefects.length > 0" class="ml-2 text-blue-600">
            （已选择 {{ selectedDefects.length }} 条）
          </span>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="flex justify-center items-center py-8">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        <span class="ml-2 text-gray-500">加载中...</span>
      </div>
      
      <!-- 表格内容 -->
      <div v-else class="overflow-x-auto">
        <table class="w-full">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <input type="checkbox" v-model="selectAll" @change="handleSelectAll($event.target.checked)" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">编号</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">线路</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">里程桩</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">等级</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">上报时间</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-if="filteredDefects.length === 0" class="hover:bg-gray-50">
              <td colspan="9" class="px-6 py-8 text-center text-gray-500">
                <i class="fas fa-inbox text-4xl mb-2 block"></i>
                暂无数据
              </td>
            </tr>
            <tr v-for="defect in filteredDefects" :key="defect.id" class="hover:bg-gray-50">
              <td class="px-6 py-4">
                <input type="checkbox" :checked="selectedDefects.includes(defect.id)" @change="handleSelect(defect.id, $event.target.checked)" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
              </td>
              <td class="px-6 py-4 text-sm font-medium text-gray-900">{{ defect.defectCode }}</td>
              <td class="px-6 py-4 text-sm text-gray-500">{{ defect.lineName }}</td>
              <td class="px-6 py-4 text-sm text-gray-500">{{ defect.milestone }}</td>
              <td class="px-6 py-4 text-sm text-gray-500">{{ getTypeText(defect.type) }}</td>
              <td class="px-6 py-4">
                <span :class="['inline-flex px-2 py-1 text-xs font-semibold rounded-full', getLevelClass(defect.level)]">
                  {{ getLevelText(defect.level) }}
                </span>
              </td>
              <td class="px-6 py-4">
                <span :class="['inline-flex px-2 py-1 text-xs font-semibold rounded-full', getStatusClass(defect.status)]">
                  {{ getStatusText(defect.status) }}
                </span>
              </td>
              <td class="px-6 py-4 text-sm text-gray-500">{{ defect.reportTime }}</td>
              <td class="px-6 py-4 text-sm">
                <div class="flex items-center gap-2">
                  <button @click="handleView(defect)" class="text-blue-600 hover:text-blue-800" title="查看详情">
                    <i class="fas fa-eye"></i>
                  </button>
                  <button @click="handleEdit(defect)" class="text-green-600 hover:text-green-800" title="编辑">
                    <i class="fas fa-edit"></i>
                  </button>
                  <button @click="handleDelete(defect)" class="text-red-600 hover:text-red-800" title="删除">
                    <i class="fas fa-trash"></i>
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 缺陷详情/编辑弹窗 -->
    <div v-if="dialogVisible" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        <div class="flex items-center justify-between p-6 border-b border-gray-200">
          <h3 class="text-lg font-semibold text-gray-900">{{ dialogTitle }}</h3>
          <button @click="dialogVisible = false" class="text-gray-400 hover:text-gray-600">
            <i class="fas fa-times text-xl"></i>
          </button>
        </div>
        
        <div class="p-6">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <!-- 缺陷编号 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">缺陷编号</label>
              <input 
                v-model="formData.defectCode" 
                :readonly="dialogMode === 'view'"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="请输入缺陷编号"
              />
            </div>
            
            <!-- 线路 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">所属线路</label>
              <select 
                v-model="formData.lineId" 
                :disabled="dialogMode === 'view'"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="">请选择线路</option>
                <option v-for="line in lineOptions" :key="line.value" :value="line.value">{{ line.label }}</option>
              </select>
            </div>
            
            <!-- 里程桩 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">里程桩位置</label>
              <input 
                v-model="formData.milestone" 
                :readonly="dialogMode === 'view'"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="如：K12+300"
              />
            </div>
            
            <!-- 缺陷类型 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">缺陷类型</label>
              <select 
                v-model="formData.type" 
                :disabled="dialogMode === 'view'"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="">请选择类型</option>
                <option v-for="type in typeOptions" :key="type.value" :value="type.value">{{ type.label }}</option>
              </select>
            </div>
            
            <!-- 缺陷等级 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">缺陷等级</label>
              <select 
                v-model="formData.level" 
                :disabled="dialogMode === 'view'"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="">请选择等级</option>
                <option v-for="level in levelOptions" :key="level.value" :value="level.value">{{ level.label }}</option>
              </select>
            </div>
            
            <!-- 缺陷状态 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">处理状态</label>
              <select 
                v-model="formData.status" 
                :disabled="dialogMode === 'view'"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option v-for="status in statusOptions" :key="status.value" :value="status.value">{{ status.label }}</option>
              </select>
            </div>
            
            <!-- 上报人 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">上报人</label>
              <input 
                v-model="formData.reporter" 
                readonly
                class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50"
                placeholder="上报人"
              />
            </div>
            
            <!-- 上报时间 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">上报时间</label>
              <input 
                v-model="formData.reportTime" 
                readonly
                class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50"
                placeholder="上报时间"
              />
            </div>
          </div>
          
          <!-- 缺陷描述 -->
          <div class="mt-4">
            <label class="block text-sm font-medium text-gray-700 mb-1">缺陷描述</label>
            <textarea 
              v-model="formData.description" 
              :readonly="dialogMode === 'view'"
              rows="4"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请详细描述缺陷情况"
            ></textarea>
          </div>
          
          <!-- 附件信息 -->
          <div v-if="formData.attachments && formData.attachments.length > 0" class="mt-4">
            <label class="block text-sm font-medium text-gray-700 mb-1">相关附件</label>
            <div class="space-y-2">
              <div v-for="(attachment, index) in formData.attachments" :key="index" class="flex items-center justify-between p-2 bg-gray-50 rounded-lg">
                <span class="text-sm text-gray-600">{{ attachment.name }}</span>
                <button class="text-blue-600 hover:text-blue-800 text-sm">下载</button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 弹窗底部按钮 -->
        <div class="flex items-center justify-end gap-3 p-6 border-t border-gray-200">
          <button @click="dialogVisible = false" class="px-4 py-2 text-gray-600 hover:text-gray-800 border border-gray-300 rounded-lg hover:bg-gray-50">
            取消
          </button>
          <button 
            v-if="dialogMode !== 'view'" 
            @click="handleSave" 
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            {{ dialogMode === 'add' ? '新建' : '保存' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { defectAPI, lineAPI } from '@/api/modules'

// 响应式数据
const defectList = ref([])
const loading = ref(false)
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  level: '',
  type: '',
  keyword: '',
  status: ''
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogMode = ref('') // add, edit, view
const formData = reactive({
  id: null,
  defectCode: '',
  lineId: '',
  lineName: '',
  milestone: '',
  type: '',
  level: '',
  description: '',
  reporter: '',
  reportTime: '',
  status: 'pending',
  attachments: []
})

// 表单验证规则
const formRules = {
  defectCode: [{ required: true, message: '请输入缺陷编号', trigger: 'blur' }],
  lineId: [{ required: true, message: '请选择线路', trigger: 'change' }],
  type: [{ required: true, message: '请选择缺陷类型', trigger: 'change' }],
  level: [{ required: true, message: '请选择缺陷等级', trigger: 'change' }],
  description: [{ required: true, message: '请输入缺陷描述', trigger: 'blur' }]
}

// 选择相关
const selectedDefects = ref([])
const selectAll = ref(false)

// 统计数据
const statistics = ref({
  total: 0,
  pending: 0,
  processing: 0,
  completed: 0,
  urgent: 0
})

// 线路选项
const lineOptions = ref([])

// 缺陷类型选项
const typeOptions = ref([])

// 缺陷等级选项
const levelOptions = ref([])

// 状态选项
const statusOptions = ref([
  { value: 'pending', label: '待处理', color: 'bg-yellow-100 text-yellow-800' },
  { value: 'in_progress', label: '处理中', color: 'bg-blue-100 text-blue-800' },
  { value: 'completed', label: '已完成', color: 'bg-green-100 text-green-800' },
  { value: 'closed', label: '已关闭', color: 'bg-gray-100 text-gray-800' }
])

// 计算属性
const filteredDefects = computed(() => {
  let filtered = defectList.value
  
  if (searchForm.level) {
    filtered = filtered.filter(item => item.levelId === parseInt(searchForm.level))
  }
  
  if (searchForm.type) {
    filtered = filtered.filter(item => item.typeId === parseInt(searchForm.type))
  }
  
  if (searchForm.status) {
    filtered = filtered.filter(item => item.status === searchForm.status)
  }
  
  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase()
    filtered = filtered.filter(item => 
      item.defectCode.toLowerCase().includes(keyword) ||
      item.lineName.toLowerCase().includes(keyword) ||
      item.description.toLowerCase().includes(keyword)
    )
  }
  
  return filtered
})

const statusText = computed(() => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    closed: '已关闭'
  }
  return statusText
})

const levelText = computed(() => {
  const levelMap = {
    low: '低危',
    general: '一般',
    serious: '严重',
    critical: '危急',
    high: '高危',
    emergency: '紧急'
  }
  return levelText
})

// 模拟数据
// 示例数据已移除，所有数据都从后端API获取
// 示例数据已移除，所有数据都从后端API获取

/**
 * 加载线路选项
 */
const loadLineOptions = async () => {
  try {
    const response = await lineAPI.getLines({ pageNum: 1, pageSize: 100 })
    if (response.code === 0) {
      lineOptions.value = (response.data.records || []).map(item => ({
        value: item.id,
        label: item.lineName || item.name
      }))
    }
  } catch (error) {
    console.error('加载线路选项失败:', error)
  }
}

/**
 * 加载缺陷类型选项
 */
const loadTypeOptions = async () => {
  try {
    // 从缺陷数据中提取类型信息
    const response = await defectAPI.getDefects({ pageNum: 1, pageSize: 100 })
    if (response.code === 0) {
      const types = new Map()
      const defects = response.data.records || []
      
      defects.forEach(defect => {
        if (defect.typeId && defect.typeName) {
          types.set(defect.typeId, {
            value: defect.typeId,
            label: defect.typeName
          })
        }
      })
      
      typeOptions.value = Array.from(types.values())
    }
  } catch (error) {
    console.error('加载缺陷类型选项失败:', error)
  }
}

/**
 * 加载缺陷等级选项
 */
const loadLevelOptions = async () => {
  try {
    // 从缺陷数据中提取等级信息
    const response = await defectAPI.getDefects({ pageNum: 1, pageSize: 100 })
    if (response.code === 0) {
      const levels = new Map()
      const defects = response.data.records || []
      
      defects.forEach(defect => {
        if (defect.levelId && defect.levelName) {
          const colorMap = {
            '低危': 'bg-gray-100 text-gray-800',
            '一般': 'bg-green-100 text-green-800',
            '严重': 'bg-yellow-100 text-yellow-800',
            '危急': 'bg-orange-100 text-orange-800',
            '高危': 'bg-red-100 text-red-800',
            '紧急': 'bg-red-200 text-red-900'
          }
          
          levels.set(defect.levelId, {
            value: defect.levelId,
            label: defect.levelName,
            color: colorMap[defect.levelName] || 'bg-gray-100 text-gray-800'
          })
        }
      })
      
      levelOptions.value = Array.from(levels.values())
    }
  } catch (error) {
    console.error('加载缺陷等级选项失败:', error)
  }
}

// 加载缺陷列表
const loadDefectList = async () => {
  try {
    loading.value = true
    
    const params = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      keyword: searchForm.keyword || undefined,
      status: searchForm.status || undefined,
      typeId: searchForm.type || undefined,
      levelId: searchForm.level || undefined
    }
    
    const response = await defectAPI.getDefects(params)
    
    if (response.code === 0) {
      const data = response.data
      // 映射字段名，将后端返回的字段映射到前端使用的字段
      defectList.value = (data.records || []).map(item => ({
        ...item,
        defectCode: item.code,           // 将code映射到defectCode
        type: item.typeName,             // 将typeName映射到type
        level: item.levelName,           // 将levelName映射到level
        reporter: item.reporterName,     // 将reporterName映射到reporter
        reportTime: item.reportTime      // 直接使用reportTime
        // 保持typeId和levelId不变，用于编辑/查看时的选项匹配
      }))
      
      // 更新分页信息
      pagination.value.total = data.total || 0
      pagination.value.pages = data.pages || 0
      
      // 更新统计数据
      updateStatistics()
    } else {
      throw new Error(response.message || '获取缺陷列表失败')
    }
    
  } catch (error) {
    console.error('加载缺陷列表失败:', error)
    ElMessage.error('加载缺陷列表失败')
  } finally {
    loading.value = false
  }
}

// 更新统计数据
const updateStatistics = async () => {
  try {
    const response = await defectAPI.getDefectStatistics()
    
    if (response.code === 0) {
      const data = response.data
      statistics.value = {
        total: data.totalDefects || 0,
        pending: data.pending || 0,
        processing: data.inProgress || 0,
        completed: data.completed || 0,
        urgent: data.urgent || 0
      }
    } else {
      console.error('获取缺陷统计失败:', response.message)
    }
  } catch (error) {
    console.error('获取缺陷统计失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.pageNum = 1
  loadDefectList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    level: '',
    type: '',
    keyword: '',
    status: ''
  })
  handleSearch()
}

// 刷新数据
const handleRefresh = () => {
  loadDefectList()
}

// 分页变化
const handlePageChange = (page) => {
  pagination.value.pageNum = page
  loadDefectList()
}

// 全选
const handleSelectAll = (checked) => {
  selectAll.value = checked
  if (checked) {
    selectedDefects.value = filteredDefects.value.map(item => item.id)
  } else {
    selectedDefects.value = []
  }
}

// 单选
const handleSelect = (defectId, checked) => {
  if (checked) {
    selectedDefects.value.push(defectId)
  } else {
    const index = selectedDefects.value.indexOf(defectId)
    if (index > -1) {
      selectedDefects.value.splice(index, 1)
    }
  }
  
  // 更新全选状态
  selectAll.value = selectedDefects.value.length === filteredDefects.value.length
}

// 新建缺陷
const handleAddDefect = () => {
  dialogTitle.value = '新建缺陷'
  dialogMode.value = 'add'
  Object.assign(formData, {
    id: null,
    defectCode: '',
    lineId: '',
    lineName: '',
    milestone: '',
    type: '',
    level: '',
    description: '',
    reporter: '当前用户',
    reportTime: new Date().toISOString(),
    status: 'pending',
    attachments: []
  })
  dialogVisible.value = true
}

// 编辑缺陷
const handleEdit = (defect) => {
  dialogTitle.value = '编辑缺陷'
  dialogMode.value = 'edit'
  
  // 将defect的属性赋值给formData（reactive对象）
  Object.assign(formData, {
    ...defect,
    type: defect.typeId,        // 将typeId映射到type字段，用于下拉框选择
    level: defect.levelId       // 将levelId映射到level字段，用于下拉框选择
  })
  
  dialogVisible.value = true
}

// 查看缺陷详情
const handleView = (defect) => {
  dialogTitle.value = '缺陷详情'
  dialogMode.value = 'view'
  
  // 将defect的属性赋值给formData（reactive对象）
  Object.assign(formData, {
    ...defect,
    type: defect.typeId,        // 将typeId映射到type字段，用于下拉框选择
    level: defect.levelId       // 将levelId映射到level字段，用于下拉框选择
  })
  
  dialogVisible.value = true
}

// 删除缺陷
const handleDelete = async (defect) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除缺陷 "${defect.defectCode}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await defectAPI.deleteDefect(defect.id)
    
    if (response.code === 0) {
      ElMessage.success('删除成功')
      loadDefectList()
      updateStatistics()
    } else {
      throw new Error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除缺陷失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedDefects.value.length === 0) {
    ElMessage.warning('请选择要删除的缺陷')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedDefects.value.length} 个缺陷吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await defectAPI.batchDeleteDefects(selectedDefects.value)
    
    if (response.code === 0) {
      ElMessage.success(`成功删除 ${selectedDefects.value.length} 个缺陷`)
      selectedDefects.value = []
      selectAll.value = false
      loadDefectList()
      updateStatistics()
    } else {
      throw new Error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 保存缺陷
const handleSave = async () => {
  try {
    // 表单验证
    if (!formData.lineId) {
      ElMessage.error('请选择线路')
      return
    }
    if (!formData.type) {
      ElMessage.error('请选择缺陷类型')
      return
    }
    if (!formData.level) {
      ElMessage.error('请选择缺陷等级')
      return
    }
    if (!formData.description) {
      ElMessage.error('请输入缺陷描述')
      return
    }
    
    // 构建请求数据，将前端字段映射到后端字段
    const requestData = {
      lineId: parseInt(formData.lineId),
      milestone: formData.milestone || '',
      typeId: parseInt(formData.type),
      levelId: parseInt(formData.level),
      status: formData.status || 'pending',
      location: formData.location || '',
      description: formData.description,
      reporterId: formData.reporterId || null,
      reportTime: formData.reportTime ? new Date(formData.reportTime).toISOString() : null,
      imagesJson: formData.imagesJson || null,
      remarks: formData.remarks || '',
      attachments: formData.attachments || []
    }
    
    let response
    if (dialogMode.value === 'add') {
      response = await defectAPI.createDefect(requestData)
    } else {
      response = await defectAPI.updateDefect(formData.id, requestData)
    }
    
    if (response.code === 0) {
      ElMessage.success(dialogMode.value === 'add' ? '新建缺陷成功' : '编辑缺陷成功')
      dialogVisible.value = false
      loadDefectList()
      updateStatistics()
    } else {
      throw new Error(response.message || '保存失败')
    }
    
  } catch (error) {
    console.error('保存缺陷失败:', error)
    ElMessage.error('保存缺陷失败')
  }
}

// 导出数据
const handleExport = () => {
  // 模拟导出功能
  ElMessage.info('导出功能开发中...')
}

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    pending: 'bg-yellow-100 text-yellow-800',
    in_progress: 'bg-blue-100 text-blue-800',
    completed: 'bg-green-100 text-green-800',
    closed: 'bg-gray-100 text-gray-800'
  }
  return statusMap[status] || 'bg-gray-100 text-gray-800'
}

// 获取等级样式类
const getLevelClass = (level) => {
  const levelMap = {
    // 等级键值映射
    low: 'bg-gray-100 text-gray-800',
    general: 'bg-green-100 text-green-800',
    serious: 'bg-yellow-100 text-yellow-800',
    critical: 'bg-orange-100 text-orange-800',
    high: 'bg-red-100 text-red-800',
    emergency: 'bg-red-200 text-red-900',
    // 等级名称映射
    '低危': 'bg-gray-100 text-gray-800',
    '一般': 'bg-green-100 text-green-800',
    '严重': 'bg-yellow-100 text-yellow-800',
    '危急': 'bg-orange-100 text-orange-800',
    '高危': 'bg-red-100 text-red-800',
    '紧急': 'bg-red-200 text-red-900'
  }
  return levelMap[level] || 'bg-gray-100 text-gray-800'
}

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    corrosion: '腐蚀',
    leakage: '泄漏',
    foreign_matter: '异物',
    damage: '损坏',
    other: '其他'
  }
  return typeMap[type] || type
}

// 获取等级文本
const getLevelText = (level) => {
  const levelMap = {
    low: '低危',
    general: '一般',
    serious: '严重',
    critical: '危急',
    high: '高危',
    emergency: '紧急'
  }
  return levelMap[level] || level
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    in_progress: '处理中',
    completed: '已完成',
    closed: '已关闭'
  }
  return statusMap[status] || status
}

// 初始化
onMounted(() => {
  loadDefectList()
  loadLineOptions()
  loadTypeOptions()
  loadLevelOptions()
})
</script>

<style scoped>
.toolbar { margin-bottom: 12px; display: flex; gap: 8px; }
.card { background: #fff; border: 1px solid #eee; padding: 16px; border-radius: 6px; }
</style>
